package com.zzc.webchat.member;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zzc.util.AppUtil;
import com.zzc.util.Page;
import com.zzc.util.PageData;
import com.zzc.util.Tools;
import com.zzc.util.weixin.Sign;
import com.zzc.util.weixin.TemplateUtil;
import com.zzc.util.weixin.Weixin;
import com.zzc.util.weixin.api.ErpInter;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * 
 * 类名称：WeixinController.java 类描述： 微信公共平台开发
 * 
 * @author FH 762879434 作者单位： 联系方式： 创建时间：2014年7月10日
 * @version 1.0
 */
@Controller
@RequestMapping(value = "/weixin/vip")
public class WeixinWebController extends BaseController{

	@Value("${webchat.appid}")
	private String appid;
	@Value("${webchat.appsecret}")
	private String appsecret;
	@Value("${webchat.templateId}")
	private String templateId;
	@Value("${webchat.url}")
	private String webchatUrl;
    @Value("${webchat.state}")
    private String state;
	@Resource
	private ErpInter erpApi;
	private static final String SUCCESS = "success";
    private static final String MSG = "msg";
    private static final String DATA = "data";

	/**
	 * 菜单入口
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/main")
	@ResponseBody
	public Object main(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logBefore(logger, "公众号菜单入口，拉取code");
		PageData pd = new PageData();
		Map<String, Object> map = new HashMap<String, Object>();
		List<PageData> pdList = new ArrayList<PageData>();
		// 网页授权
		logBefore(logger, "进入回调");

		response.sendRedirect(Weixin.getCode(appid, java.net.URLEncoder.encode(webchatUrl+"/weixin/vip/index", "utf-8"), "snsapi_userinfo", state));

		pd.put("msg", "ok");
		pdList.add(pd);
		map.put("list", pdList);
		logAfter(logger);
		return AppUtil.returnObject(pd, map);
	}

	/**
	 * 微信主页
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index")
	public ModelAndView index(Page page) throws Exception {
		logBefore(logger, "微信主页");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		JSONObject user = getUser();
		// 如果未检测到微信用户信息。则重新拉取授权信息
		if (null == user || user.isNullObject()) {
			logger.info("从微信拉取用户信息");
			if (null == pd.get("code") || "".equals(pd.get("code"))) {
				mv.addObject("exception", "code失效");
				mv.setViewName("wx_error");
				return mv;
			}
			// 拉取微信用户授权
			String rs = this.getUserInfoWX(appid, appsecret, pd.get("code").toString());
			if (!"ok".equals(rs)) {
				mv.addObject("exception", "拉取用户信息出错。错误码:" + rs);
				mv.setViewName("wx_error");
				return mv;
			}
			user = getUser();
		}
		pd.putAll(user);
		logBefore(logger, "拉取ERP用户信息");
		JSONObject jsonObject = erpApi.getUser(user.getString("openid"));
		if(!jsonObject.has(SUCCESS)){
            mv.addObject("exception", "服务器异常:" + jsonObject.get(MSG));
            mv.setViewName("wx_error");
            return mv;
        }
		if (!jsonObject.getBoolean(SUCCESS)) {
            pd.put("msg", "未注册");
            mv.addObject("pd", pd);
            mv.setViewName("weixin/vip/register_edit");
            return mv;
		}
		jsonObject = jsonObject.getJSONObject(DATA);
		user.put("name", jsonObject.get("name"));
		user.put("xb", jsonObject.get("xb"));
		user.put("csrq", jsonObject.get("csrq"));
		user.put("sjh", jsonObject.get("sjh"));
		user.put("dz", jsonObject.get("dz"));
		user.put("dq", jsonObject.get("dq"));
		user.put("email", jsonObject.get("email"));
		user.put("kh", jsonObject.get("kh"));
		setUser(user);
		
		pd.putAll(JSONObject.fromObject(jsonObject));
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/homepage");
		logAfter(logger);
		return mv;
	}

	/**
	 * 微信JS 签名计算
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/wxConfig")
	@ResponseBody
	public Object wxConfig() throws Exception {
		logBefore(logger, "计算签名");
		PageData pd = this.getPageData();
		/*Map<String, Object> map = new HashMap<String, Object>();
		List<PageData> pdList = new ArrayList<PageData>();*/
		JSONObject user = getUser();
		Map<String, String> signMap = Sign.sign(Weixin.getJsapi_ticket(appid, appsecret), pd.getString("url"));
		if (null == signMap.get("jsapi_ticket")) {
			pd.put("msg", "no");
		} else {
			pd.putAll(signMap);
			pd.put("openid", user.get("openid"));
			pd.put("appid", appid);
			pd.put("msg", "ok");
		}

		/*pdList.add(pd);
		map.put("list", pdList);*/
		logAfter(logger);
		return pd;
	}
	
	/**
	 * 验证码发送
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sendMsg")
	@ResponseBody
	public Object sendMsg() throws Exception {
		logBefore(logger, "验证码发送");
		PageData pd = this.getPageData();
		String randomNum = Tools.getRandomNum() + "";
		pd.put("randomNum", randomNum);
		pd.put("result", erpApi.sendMsg(pd));
		logAfter(logger);
		return pd;
	}

	/**
	 * 用户注册
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register")
	public ModelAndView register(Page page) throws Exception {
		logBefore(logger, "用户注册");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.register(getUser(), pd.getString("name"), pd.getString("csrq"), pd.getString("sjh"));
        if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
			mv.addObject("exception", "绑定出错。错误码:" + jsonObject.get(MSG) == null ? "未知" : jsonObject.get(MSG));
			mv.setViewName("wx_error");
			return mv;
		}
		mv.setViewName("redirect:/weixin/vip/index");
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 个人资料修改
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/editUser")
	public ModelAndView editUser(Page page) throws Exception {
		logBefore(logger, "个人资料修改");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		JSONObject jsonObject = erpApi.upUser(pd);
		if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
			mv.addObject("exception", "绑定出错。错误码:" + jsonObject.get(MSG) == null ? "未知" : jsonObject.get(MSG));
			mv.setViewName("wx_error");
			return mv;
		}
		mv.setViewName("redirect:/weixin/vip/index");
		logAfter(logger);
		return mv;
	}
	/**
	 * 去 个人资料修改页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goEditUser")
	public ModelAndView goEditUser(Page page) throws Exception {
		logBefore(logger, "去 个人资料修改页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		pd.putAll(getUser());
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/user_edit");
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 去手机号绑定页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goSjhEdit")
	public ModelAndView goSjhEdit(Page page) throws Exception {
		logBefore(logger, "去 更换手机号页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		pd.putAll(getUser());
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/sjh_edit");
		logAfter(logger);
		return mv;
	}
	/**
	 * 手机号修改
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sjhEdit")
	public ModelAndView sjhEdit(Page page) throws Exception {
		logBefore(logger, "手机号");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		String inSjh=pd.getString("sjh");
		pd.putAll(getUser());
		pd.put("sjh", inSjh);
		JSONObject jsonObject = erpApi.upUser(pd);
        if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
            mv.addObject("exception", "绑定出错。错误码:" + jsonObject.get(MSG) == null ? "未知" : jsonObject.get(MSG));
			mv.setViewName("wx_error");
			return mv;
		}
		mv.setViewName("redirect:/weixin/vip/index");
		logAfter(logger);
		return mv;
	}
	/**
	 * 去绑定页面
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goBind")
	public ModelAndView goBind(Page page) throws Exception {
		logBefore(logger, "进入绑定");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		pd.putAll(getUser());
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/bind_edit");
		logAfter(logger);
		return mv;
	}

	/**
	 * 绑定
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/bind")
	public ModelAndView bind(Page page) throws Exception {
		logBefore(logger, "开始绑定");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.bind(pd);
        if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
			mv.setViewName("wx_error");
            mv.addObject("exception", "绑定出错。错误码:" + jsonObject.get(MSG) == null ? "未知" : jsonObject.get(MSG));
			return mv;
		}
		mv.setViewName("redirect:/weixin/vip/index");
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 去条码页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goBarcode")
	public ModelAndView goBarcode(Page page) throws Exception {
		logBefore(logger, "去条码页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		pd.putAll(getUser());
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/barcode");
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 优惠券码
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goCouponCode")
	public ModelAndView goCouponCode(Page page) throws Exception {
		logBefore(logger, "去条码页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		//pd.putAll(Jurisdiction.getUserWX());
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/coupon_code");
		logAfter(logger);
		return mv;
	}
	/**
	 * 查询积分
	 * 
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getIntegralDetails")
	@ResponseBody
	public Object getIntegralDetails() throws Exception {
		logBefore(logger, "积分记录明细查询");
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.getIntegralDetails(pd);
		pd.put("data", jsonObject);
		logAfter(logger);
		return pd;
	}
	
	/**
	 * 获取优惠券
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCouponList")
	@ResponseBody
	public Object getCouponList() throws Exception {
		logBefore(logger, "积分记录明细查询");
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.getCouponList(pd);
		pd.put("data", jsonObject);
		logAfter(logger);
		return pd;
	}
	
	/**
	 * 去积分页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goIntegralDetails")
	public ModelAndView goIntegralDetails(Page page) throws Exception {
		logBefore(logger, "积分记录");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/integral_list");
		logAfter(logger);
		return mv;
	}
	

	/**
	 * 查看优惠卷页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goCouponList")
	public ModelAndView goCouponList(Page page) throws Exception {
		logBefore(logger, "查看优惠卷");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/coupon_list");
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 去消费记录页面
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goOrders")
	public ModelAndView goOrders(Page page) throws Exception {
		logBefore(logger, "消费记录");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/order_list");
		logAfter(logger);
		return mv;
	}
	/**
	 * 消费记录查询
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getOrders")
	@ResponseBody
	public Object getOrders() throws Exception {
		logBefore(logger, "消费记录查询");
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.getOrders(pd);
		pd.put("data", jsonObject);
		logAfter(logger);
		return pd;
	}

	/**
	 * 消费明细查询
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getOrderDetails")
	public ModelAndView getOrderDetails(Page page) throws Exception {
		logBefore(logger, "单笔消费记录明细查询");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.getOrderDetails(pd);
        if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
			mv.setViewName("wx_error");
			mv.addObject("exception", "查询出错。错误码:" + jsonObject.get(MSG));
			return mv;
		}
		mv.addObject("list", jsonObject.get(DATA));
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/order_detail_list");
		logAfter(logger);
		return mv;
	}
	@RequestMapping(value = "/getLocal")
	@ResponseBody
	public Object getLocal() throws Exception {
		logBefore(logger, "查看附近门店");
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.getLocal(pd);
		pd.put("data", jsonObject);
		logAfter(logger);
		return pd;
	}
	/**
	 * 附近门店
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goLocal")
	public ModelAndView goLocal(Page page) throws Exception {
		logBefore(logger, "附近门店");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		mv.addObject("pd", pd);
		mv.setViewName("weixin/vip/local_list");
		logAfter(logger);
		return mv;
	}
	
	/**
	 * 积分说明
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getIntegral")
	public ModelAndView getIntegral(Page page) throws Exception {
		logBefore(logger, "积分说明");
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("weixin/vip/integral");
		logAfter(logger);
		return mv;
	}
	/**
	 * 去签到
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goSign")
	public ModelAndView goSign(Page page) throws Exception {
		logBefore(logger, "goSign");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		pd.put("openid", getUser().get("openid"));	//Jurisdiction.getUserWX().get("openid")
		mv.setViewName("weixin/vip/sign");
		JSONObject jsonObject = erpApi.getSignDetail(pd);
		pd.putAll(jsonObject);
		mv.addObject("pd", pd);
        if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
			mv.addObject("exception", "加载出错。错误码:" + jsonObject.get(MSG));
			mv.setViewName("wx_error");
		}
		logAfter(logger);
		return mv;
	}
	/**
	 * 签到
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/sign")
	public ModelAndView sign(Page page) throws Exception {
		logBefore(logger, "sign");
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		JSONObject jsonObject = erpApi.sign(pd);
		mv.setViewName("redirect:/weixin/vip/goSign");
        if (!jsonObject.has(SUCCESS) || !jsonObject.getBoolean(SUCCESS)) {
			mv.addObject("exception", "加载出错。错误码:" + jsonObject.get(MSG));
			mv.setViewName("wx_error");
		}
		logAfter(logger);
		return mv;
	}
	@RequestMapping(value = "/wx_error")
	public ModelAndView wx_error(Page page) throws Exception {
		logBefore(logger, "积分说明");
		ModelAndView mv = this.getModelAndView();
		mv.addObject("exception", "请在微信内打开链接");
		mv.setViewName("wx_error");
		logAfter(logger);
		return mv;
	}
	/**
	 * 拉取微信授权
	 * 
	 * @param appid
	 * @param appsecret
	 * @param code
	 * @return
	 * @throws Exception
	 */
	private String getUserInfoWX(String appid, String appsecret, String code) throws Exception {
		JSONObject jsonObject = Weixin.getByCodeAccess_token(appid, appsecret, code);
		if (!jsonObject.has("access_token")) {
			return jsonObject.toString();
		}
		JSONObject jsonUser = Weixin.getUserInfo(jsonObject.getString("access_token"), jsonObject.getString("openid"));
		jsonUser.put("appid", appid);
		jsonUser.put("appsecret", appsecret);
		setUser(jsonUser);
		if (!jsonUser.has("openid")) {
			return jsonUser.toString();
		}
		return "ok";
	}
//	private void sendMsg(String beizhu){
//		Map<String,String> data = new LinkedHashMap<String, String>();
//		Map<String,String> datas = new LinkedHashMap<String, String>();
//		data.put("first", "尊敬的会员，您在本店成功消费!");
//		data.put("keyword1", "cardno");
//		data.put("keyword1", "money");
//		data.put("keyword1", "time");
//		data.put("keyword1", "消费门店");
//
//		datas.put("测试参数1", "11");
//		datas.put("测试参数2", "22");
//		datas.put("测试参数3", "33");
//		datas.put("测试参数4", "44");
//		datas.put("\\", "n");
//		datas.put("测试参数6", "66");
//		String remark ="更多详细信息，请前往微信会员中心查看！";
//		String url = "http://1a9397082e.51mypc.cn/ssmerp/weixin/vip/main?USERNAME=CDZFRJ";
//		JSONObject user = getUser();
//		JSONObject  s = Weixin.sendTemplateMsg(appid, appsecret, TemplateUtil.toTemplateMsgText(user.getString("openid"), templateId, url, remark, data, datas));
//		System.out.println(s);
//	}
	/**
	 * 公众号模板消息推送
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/WXSendMsg")
	@ResponseBody
	public Object wxSendMsg(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
	    logBefore(logger, "公众号模板消息推送");
		BufferedReader br = new BufferedReader(new InputStreamReader(
				request.getInputStream(), "UTF-8"));
		String line = "";
		StringBuilder bf = new StringBuilder();
		while ((line = br.readLine()) != null) {
			bf.append(line);
		}
		logger.info("parms:" + bf.toString());
		JSONObject jsonObject = JSONObject.fromObject(bf.toString());

		Map<String,String> data = JSONObject.fromObject(jsonObject.get("data"));
		Map<String,String> datas = JSONObject.fromObject(jsonObject.get("datas"));
		JSONObject json = Weixin.sendTemplateMsg(appid, appsecret,
				TemplateUtil.toTemplateMsgText(
						jsonObject.getString("openid"), templateId,
						webchatUrl+"/main", jsonObject.getString("remark"), data, datas));
		logger.info(json.toString());
		logAfter(logger);
		return "ok";
	}
}
